package com.cincc.cinccimdemo.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.adapter.MainPagerAdapter;
import com.cincc.cinccimdemo.common.AttrConstants;
import com.cincc.cinccimdemo.qrcode.ScanQRCodeActivity;
import com.cincc.cinccimdemo.ui.contact.ContactFragment;
import com.cincc.cinccimdemo.ui.contact.CreateGroupActivity;
import com.cincc.cinccimdemo.ui.conversation.detail.GroupDetailActivity;
import com.cincc.cinccimdemo.ui.conversationlist.ConversationListFragment;
import com.cincc.cinccimdemo.ui.main.GroupInfoActivity;
import com.cincc.cinccimdemo.ui.main.SearchUserActivity;
import com.cincc.cinccimdemo.ui.me.MineFragment;
import com.cincc.cinccimdemo.ui.main.SearchContactActivity;
import com.cincc.cinccimdemo.ui.main.SearchRecordActivity;
import com.cincc.cinccimdemo.widget.ViewPagerFixed;
import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.table.IMContactGroup;
import com.cincc.im.util.ImManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.king.zxing.Intents;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends IMBaseActivity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "MainActivity";
    ViewPagerFixed contentViewPager;
    LinearLayout contentLinearLayout;
    BottomNavigationView bottomNavigationView;

    private final List<Fragment> mFragmentList = new ArrayList<>(3);
    private static final int REQUEST_CODE_SCAN_QR_CODE = 100;
    private static final int REQUEST_CODE_PICK_CONTACT = 101;

    @Override
    protected void bindViews() {
        super.bindViews();
        contentViewPager = findViewById(R.id.contentViewPager);
        contentLinearLayout = findViewById(R.id.contentLinearLayout);
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        BindSipEvent();

        initView();

//        ImManager.getInstance().getWorkHandler().post(() -> {
//            List<IMContactGroup> friendInfos = IMSipPhoneCtrl.getInstance().getGroupList();
//        });
    }

    ConversationListFragment conversationListFragment;
    ContactFragment contactFragment;
    MineFragment mineFragment;

    private void initView() {
        conversationListFragment = new ConversationListFragment();
        contactFragment = new ContactFragment();
        mineFragment = new MineFragment();

        mFragmentList.add(conversationListFragment);
        mFragmentList.add(contactFragment);
        mFragmentList.add(mineFragment);

        contentViewPager.setAdapter(new MainPagerAdapter(getSupportFragmentManager(), mFragmentList));
        contentViewPager.setOnPageChangeListener(this);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.navigation_1:
                    contentViewPager.setCurrentItem(0, false);
                    setTitle("聊天");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.gray5, false);
                    }
                    break;
                case R.id.navigation_2:
                    contentViewPager.setCurrentItem(1, false);
                    setTitle("通讯录");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.gray5, false);
                    }
                    break;
                case R.id.navigation_3:
                    contentViewPager.setCurrentItem(2, false);
                    setTitle("我的");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.white, false);
                    }
                    break;
                default:
                    break;
            }
            return true;
        });
    }

    @Override
    protected void afterViews() {
        super.afterViews();
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean showHomeMenuItem() {
        return false;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    protected int menu() {
        return R.menu.main;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
                showSearchPortal();
                break;
            case R.id.chat:
                createConversation();
                break;
            case R.id.add_contact:
                addUser();
                break;
            case R.id.scan_qrcode:
                String[] permissions = new String[]{Manifest.permission.CAMERA};
                if (!checkPermission(permissions)) {
                    requestPermissions(permissions, REQUEST_CODE_SCAN_QR_CODE);
                    return true;
                }
                startActivityForResult(new Intent(this, ScanQRCodeActivity.class), REQUEST_CODE_SCAN_QR_CODE);
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showSearchPortal() {
        if (contentViewPager.getCurrentItem() == 0) {
            Intent intent = new Intent(this, SearchRecordActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, SearchContactActivity.class);
            startActivity(intent);
        }
    }

    private void createConversation() {
        Intent i = new Intent(this, CreateGroupActivity.class);
        startActivity(i);
    }

    private void addUser() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        startActivity(intent);
    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                bottomNavigationView.setSelectedItemId(R.id.navigation_1);
                break;
            case 1:
                bottomNavigationView.setSelectedItemId(R.id.navigation_2);
                contactFragment.refreshData();
                break;
            case 2:
                bottomNavigationView.setSelectedItemId(R.id.navigation_3);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_SCAN_QR_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivity(new Intent(this, ScanQRCodeActivity.class));
            } else {
                Toast.makeText(this, "打开拍照权限失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_SCAN_QR_CODE:
                String result = data.getStringExtra(Intents.Scan.RESULT);
                onScanPcQrCode(result);
                break;
//            case REQUEST_CODE_PICK_CONTACT:
//                UserInfo userInfo = data.getParcelableExtra("userInfo");
//                if (userInfo != null) {
//                    createSecretChat(userInfo.uid);
//                }
//                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    private void onScanPcQrCode(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has("type") && jsonObject.has("targetId")) {
                if (jsonObject.getInt("type") == 0) {

                } else {
                    Intent i = new Intent(this, GroupInfoActivity.class);
                    i.putExtra(AttrConstants.GROUP_ID, jsonObject.getString("targetId"));
                    startActivity(i);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "onScanPcQrCode: " + e.getMessage());
        }
    }
}
